package com.yonyou.crm.common.type.handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

@MappedJdbcTypes({JdbcType.TIMESTAMP})
@MappedTypes({Date.class})
public class CrmTimestampHandler extends BaseTypeHandler<Date> {

	@Override
	public Date getNullableResult(ResultSet resultSet, String s)
			throws SQLException {
		return new Date(resultSet.getLong(s));
	}

	@Override
	public Date getNullableResult(ResultSet resultSet, int i)
			throws SQLException {
		return new Date(resultSet.getLong(i));
	}

	@Override
	public Date getNullableResult(CallableStatement callableStatement, int i)
			throws SQLException {
		return callableStatement.getDate(i);
	}

	@Override
	public void setNonNullParameter(PreparedStatement preparedStatement, int i, Date date, JdbcType jdbcType) throws SQLException {
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date clearDate = null;
		try {
			clearDate = sdf.parse("0001-01-01 00:00:00");
		} catch (ParseException e) {
		}
		if (clearDate.equals(date)) {
			preparedStatement.setDate(i, null);
		}
		else {
			preparedStatement.setTimestamp(i, new java.sql.Timestamp(date.getTime()));
		}
	}

}
